import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class WriteExcelDemo2 {
    public static void main(String[] args) {

        WriteCellStyle cellStyle = new WriteCellStyle();
        //设置字体居中
        cellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        //设置字体样式
        WriteFont font = new WriteFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)12);
        cellStyle.setWriteFont(font);

        HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(cellStyle, cellStyle);
		
        //生成Excel报表
        EasyExcel.write("E:/报表2.xlsx")
                .excelType(ExcelTypeEnum.XLSX)
                .head(header()) //表头
                .registerWriteHandler(styleStrategy)
                .registerWriteHandler(new MyColumnStyle())
                .sheet("笑傲江湖")
                .doWrite(data());//数据行
    }

    //组装表头信息
    private static List<List<String>> header() {
        List<List<String>> list = new ArrayList<List<String>>();
        list.add(Arrays.asList("编号"));
        list.add(Arrays.asList("姓名"));
        list.add(Arrays.asList("年龄"));
        list.add(Arrays.asList("性别"));
        list.add(Arrays.asList("描述"));
        return list;
    }


    //组装表头信息
    private static List<List<String>> data() {
        List<List<String>> list = new ArrayList<List<String>>();
        list.add(Arrays.asList("1","风清扬","88","男","独孤九剑"));
        list.add(Arrays.asList("2","令狐冲","28","男","易筋经"));
        list.add(Arrays.asList("3","任盈盈","25","女","魔教圣姑"));
        list.add(Arrays.asList("4","任我行","60","男","吸星大法"));
        list.add(Arrays.asList("5","东方不败","48","男/女","葵花宝典"));
        return list;
    }
    static class MyColumnStyle extends AbstractColumnWidthStyleStrategy {
        protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList,
                                      Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
            writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), 4500);
        }
    }
}